package cn.itsource.template;

import cn.hutool.http.HttpUtil;
import cn.itsource.config.WechatConfig;
import cn.itsource.domain.AccessTokenResult;
import cn.itsource.domain.OpenIdResult;
import cn.itsource.domain.PhoneNumberResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program fccar_tt
 * @Description
 * @Author TT
 * @Date 2024/09/04 12:40
 * @Version 1.0
 */
@Component
public class WechatTemplate {
    @Autowired
    private WechatConfig wechatConfig;

    public WechatTemplate(WechatConfig wechatConfig) {
        this.wechatConfig = wechatConfig;
    }

    //微信登录：获取Token
    public String getOpenId(String code){
        //拼接请求路径
        String url = String.format(WechatConfig.WUrl, wechatConfig.getAppid(),wechatConfig.getSecret(), code);
        //发送请求，返回的是JSON格式
        String s = HttpUtil.get(url);
        //将json格式转化为对象
        OpenIdResult openIdResult = JSON.parseObject(s, OpenIdResult.class);
        //获取openIdResult对象里的Openid
        return openIdResult.getOpenid();
    }

    /**
     * 获取accessToken
     * */
    public String getPhoneNumber(String code){
        //拼接请求路径
        String accessTokenUrl =
                String.format(WechatConfig.ACCESSTOKEN_URL,wechatConfig.getAppid(),wechatConfig.getSecret());
        //发送请求，返回的是json格式的数据
        String s = HttpUtil.get(accessTokenUrl);
        //将json格式转换为对象
        AccessTokenResult accessTokenResult = JSON.parseObject(s, AccessTokenResult.class);
        return getWechatPhone(accessTokenResult.getAccess_token(),code);
    }

    /**
     * 根据获取到的accessToken去获取手机号
     * */
    public static String getWechatPhone(String accessToken,String phoneCode){
        //拼接请求路径
        String phoneNumberUrl = String.format(WechatConfig.PHONENUMBER_URL, accessToken);
        Map<String, Object> map = new HashMap<>();
        map.put("code",phoneCode);
        String result = HttpUtil.post(phoneNumberUrl,map);
        /**
         * 方式一：将JSON格式转换为实体类
         * */
        //PhoneNumberResult phoneNumberResult = JSON.parseObject(s, PhoneNumberResult.class);
        //return phoneNumberResult.getPhoneInfoResult().getPhoneNumber();
        /**
         * 方式二
         * */
        //s就是一个map集合
        JSONObject jsonObject = JSON.parseObject(result);
        //通过phone_info(该属性是一个对象)这个key键去该键的值对象
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.get("phoneNumber").toString();
        return phoneNumber;
    }
}
